package com.tc.have_a_tired.ui;

import com.tc.have_a_tired.service.RestReminderService;
import com.tc.have_a_tired.util.Constants;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 系统托盘管理类
 */
public class SystemTrayManager {

    private TrayIcon trayIcon;
    private RestReminderService reminderService;
    private Frame parentFrame;

    public SystemTrayManager(RestReminderService reminderService, Frame parentFrame) {
        this.reminderService = reminderService;
        this.parentFrame = parentFrame;
    }

    /**
     * 创建系统托盘图标
     */
    public boolean createTrayIcon() {
        if (!SystemTray.isSupported()) {
            System.err.println("系统托盘不支持");
            return false;
        }

        SystemTray systemTray = SystemTray.getSystemTray();

        // 创建托盘图标（使用简单的图标）
        Image image = createTrayImage();
        trayIcon = new TrayIcon(image, Constants.APP_NAME);
        trayIcon.setImageAutoSize(true);

        // 创建弹出菜单
        PopupMenu popupMenu = createPopupMenu();
        trayIcon.setPopupMenu(popupMenu);

        // 双击图标显示设置窗口
        trayIcon.addActionListener(e -> {
            EventQueue.invokeLater(this::showSettings);
        });

        try {
            systemTray.add(trayIcon);
            return true;
        } catch (AWTException e) {
            System.err.println("无法添加系统托盘图标: " + e.getMessage());
            return false;
        }
    }

    /**
     * 创建托盘图标图像
     */
    private Image createTrayImage() {
        // 创建一个简单的图标
        BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制一个简单的时钟图标
        g.setColor(new Color(70, 130, 180));
        g.fillOval(2, 2, 12, 12);
        g.setColor(Color.WHITE);
        g.setStroke(new BasicStroke(1.5f));
        g.drawLine(8, 8, 8, 5); // 时针
        g.drawLine(8, 8, 11, 8); // 分针

        g.dispose();
        return image;
    }

    /**
     * 创建弹出菜单
     */
    private PopupMenu createPopupMenu() {
        PopupMenu menu = new PopupMenu();

        MenuItem settingsItem = new MenuItem("设置...");
        settingsItem.addActionListener(e -> showSettings());
        menu.add(settingsItem);

        MenuItem aboutItem = new MenuItem("关于");
        aboutItem.addActionListener(e -> showAbout());
        menu.add(aboutItem);

        menu.addSeparator();

        MenuItem exitItem = new MenuItem("退出");
        exitItem.addActionListener(e -> exitApplication());
        menu.add(exitItem);

        return menu;
    }

    /**
     * 显示设置窗口
     */
    private void showSettings() {
        EventQueue.invokeLater(() -> {
            SettingsWindow settingsWindow = new SettingsWindow(parentFrame, reminderService, this);
            settingsWindow.setVisible(true);
        });
    }

    /**
     * 显示关于对话框
     */
    private void showAbout() {
        String message = String.format(
                "%s\n\n" +
                        "版本: 1.0\n" +
                        "功能: 定时提醒休息，保护身体健康\n\n" +
                        "当前设置:\n" +
                        "• 提醒间隔: %d 分钟\n" +
                        "• 休息时长: %d 分钟",
                Constants.APP_NAME,
                com.tc.have_a_tired.config.ConfigManager.getReminderInterval(),
                com.tc.have_a_tired.config.ConfigManager.getRestDuration());

        JOptionPane.showMessageDialog(
                parentFrame,
                message,
                "关于",
                JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 退出应用（带确认对话框）
     */
    private void exitApplication() {
        int result = JOptionPane.showConfirmDialog(
                parentFrame,
                "确定要退出吗？",
                "确认退出",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);

        if (result == JOptionPane.YES_OPTION) {
            exitApplicationDirectly();
        }
    }

    /**
     * 直接退出应用（不显示确认对话框）
     */
    public void exitApplicationDirectly() {
        if (reminderService != null) {
            reminderService.stop();
        }
        if (trayIcon != null) {
            SystemTray.getSystemTray().remove(trayIcon);
        }
        System.exit(0);
    }

    /**
     * 显示托盘通知
     */
    public void showNotification(String title, String message) {
        if (trayIcon != null) {
            trayIcon.displayMessage(title, message, TrayIcon.MessageType.INFO);
        }
    }

    /**
     * 移除托盘图标
     */
    public void removeTrayIcon() {
        if (trayIcon != null) {
            SystemTray.getSystemTray().remove(trayIcon);
        }
    }
}
